package main

import (
	"io"
	"log"
	"net"
	"time"

	pb "github.com/zoujiaqing/smartbox-agent-gateway/src/protocol"

	"google.golang.org/grpc"
)

type server struct {
	pb.UnimplementedGatewayServer
}

func (s server) Ping(srv pb.Gateway_PingServer) error {

	log.Println("start new server")
	ctx := srv.Context()

	for {

		// exit if context is done
		// or continue
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}

		// receive data from stream
		req, err := srv.Recv()
		if err == io.EOF {
			// return will close stream from server side
			log.Println("exit")
			return nil
		}
		if err != nil {
			log.Printf("receive error %v", err)
			continue
		}

		log.Printf("Agent client timestamp: %d", req.Timestamp)

		// 生成本机时间戳
		startTime := time.Now()
		now := startTime.Unix()
		resp := pb.PongResponse{Timestamp: now}
		if err := srv.Send(&resp); err != nil {
			log.Printf("send error %v", err)
		}
		log.Printf("send gateway timestamp: %d", now)
	}
}

func main() {
	// create listener
	lis, err := net.Listen("tcp", ":50005")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	// create grpc server
	s := grpc.NewServer()
	pb.RegisterGatewayServer(s, &server{})

	// and start...
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
